from takeaway.model.user import db, User, Address


def select_user_by_phone(phone):
    return db.session.execute(db.select(User).filter_by(phone=phone)).scalar()


def insert_user(data):
    user = User(**data)
    db.session.add(user)
    db.session.commit()
    return user


def select_user_by_id(user_id):
    return db.session.execute(db.select(User).filter_by(id=user_id)).scalar()


def select_addresses(user_id):
    return db.session.execute(db.Select(Address).filter_by(user_id=user_id)).scalars()


def insert_address(user_id, name, phone, place):
    a = Address(name=name, phone=phone, place=place, user_id=user_id)
    db.session.add(a)
    db.session.commit()
    return a


def select_address(user_id, address_id):
    return db.session.execute(db.Select(Address).filter_by(user_id=user_id, id=address_id)).scalar()


def update_address(address, **kwargs):
    allow_set_names = {"name", "phone", "place"}
    for name, value in kwargs.items():
        if name in allow_set_names:
            setattr(address, name, value)
    db.session.commit()
    return address
